<template>
  <div class="user-container">
    <div class="search-bar">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-input-search
            v-model="searchKeyword"
            placeholder="请输入用户名/昵称/手机号"
            @search="handleSearch"
          />
        </a-col>
        <a-col :span="18" style="text-align: right">
          <a-button type="primary" @click="handleAdd">
            <template #icon><icon-plus /></template>
            新增用户
          </a-button>
        </a-col>
      </a-row>
    </div>

    <a-table
      :data="userList"
      :loading="loading"
      :pagination="pagination"
      @page-change="onPageChange"
    >
      <template #columns>
        <a-table-column title="用户名" data-index="username" />
        <a-table-column title="昵称" data-index="nickname" />
        <a-table-column title="手机号" data-index="phone" />
        <a-table-column title="邮箱" data-index="email" />
        <a-table-column title="角色" data-index="roles">
          <template #cell="{ record }">
            <a-space>
              <a-tag v-for="role in record.roles" :key="role.id">
                {{ role.roleName }}
              </a-tag>
            </a-space>
          </template>
        </a-table-column>
        <a-table-column title="状态" data-index="status" align="center">
          <template #cell="{ record }">
            <a-switch
              :model-value="record.status === 1"
              @change="(value) => handleStatusChange(record, value)"
              :disabled="record.isAdmin"
            />
          </template>
        </a-table-column>
        <a-table-column title="最后登录时间" data-index="lastLoginTime">
          <template #cell="{ record }">
            {{ formatDate(record.lastLoginTime) }}
          </template>
        </a-table-column>
        <a-table-column title="操作" align="center">
          <template #cell="{ record }">
            <a-space>
              <a-button type="text" @click="handleEdit(record)" :disabled="record.isAdmin">
                编辑
              </a-button>
              <a-button type="text" @click="handleRole(record)">
                角色
              </a-button>
              <a-button type="text" @click="handleResetPwd(record)">
                重置密码
              </a-button>
              <a-popconfirm
                content="确认删除该用户吗？"
                @ok="handleDelete(record)"
                :disabled="record.isAdmin"
              >
                <a-button type="text" status="danger" :disabled="record.isAdmin">
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>

    <!-- 用户表单对话框 -->
    <a-modal
      v-model:visible="dialogVisible"
      :title="formTitle"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-form :model="userForm" ref="userFormRef">
        <a-form-item field="username" label="用户名" :rules="[{ required: true, message: '请输入用户名' }]">
          <a-input v-model="userForm.username" placeholder="请输入用户名" :disabled="isEdit" />
        </a-form-item>
        <a-form-item
          field="password"
          label="密码"
          :rules="[{ required: !isEdit, message: '请输入密码' }]"
          v-if="!isEdit"
        >
          <a-input-password v-model="userForm.password" placeholder="请输入密码" />
        </a-form-item>
        <a-form-item field="nickname" label="昵称" :rules="[{ required: true, message: '请输入昵称' }]">
          <a-input v-model="userForm.nickname" placeholder="请输入昵称" />
        </a-form-item>
        <a-form-item field="phone" label="手机号">
          <a-input v-model="userForm.phone" placeholder="请输入手机号" />
        </a-form-item>
        <a-form-item field="email" label="邮箱">
          <a-input v-model="userForm.email" placeholder="请输入邮箱" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 分配角色对话框 -->
    <a-modal
      v-model:visible="roleDialogVisible"
      title="分配角色"
      @ok="handleRoleSubmit"
      @cancel="() => roleDialogVisible = false"
    >
      <a-transfer
        v-model="selectedRoleIds"
        :data="roleList"
        :filter="filterRole"
        :show-search="true"
      >
        <template #item="{ option }">
          {{ option.roleName }}
        </template>
      </a-transfer>
    </a-modal>

    <!-- 重置密码对话框 -->
    <a-modal
      v-model:visible="pwdDialogVisible"
      title="重置密码"
      @ok="handlePwdSubmit"
      @cancel="() => pwdDialogVisible = false"
    >
      <a-form :model="pwdForm" ref="pwdFormRef">
        <a-form-item
          field="newPassword"
          label="新密码"
          :rules="[{ required: true, message: '请输入新密码' }]"
        >
          <a-input-password v-model="pwdForm.newPassword" placeholder="请输入新密码" />
        </a-form-item>
        <a-form-item
          field="confirmPassword"
          label="确认密码"
          :rules="[{ required: true, message: '请确认新密码' }]"
        >
          <a-input-password v-model="pwdForm.confirmPassword" placeholder="请确认新密码" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconPlus } from '@arco-design/web-vue/es/icon'
import request from '@/api/request'

// 数据列表
const userList = ref([])
const loading = ref(false)
const searchKeyword = ref('')

// 分页配置
const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true
})

// 表单相关
const dialogVisible = ref(false)
const formTitle = ref('')
const userForm = ref({
  id: null,
  username: '',
  password: '',
  nickname: '',
  phone: '',
  email: ''
})
const userFormRef = ref()
const isEdit = computed(() => userForm.value.id !== null)

// 角色相关
const roleDialogVisible = ref(false)
const roleList = ref([])
const selectedRoleIds = ref([])
const currentUser = ref(null)

// 重置密码相关
const pwdDialogVisible = ref(false)
const pwdForm = ref({
  userId: null,
  newPassword: '',
  confirmPassword: ''
})
const pwdFormRef = ref()

// 获取用户列表
const getUserList = async () => {
  try {
    loading.value = true
    const res = await request.get('/api/SysUser/list', {
      params: {
        keyword: searchKeyword.value,
        pageIndex: pagination.value.current,
        pageSize: pagination.value.pageSize
      }
    })
    userList.value = res.data.items
    pagination.value.total = res.data.total
  } catch (error) {
    Message.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 获取角色列表
const getRoleList = async () => {
  try {
    const res = await request.get('/api/SysRole/list')
    roleList.value = res.data.map(role => ({
      key: role.id,
      ...role
    }))
  } catch (error) {
    Message.error('获取角色列表失败')
  }
}

// 获取用户角色
const getUserRoles = async (userId) => {
  try {
    const res = await request.get(`/api/SysUser/${userId}/roles`)
    // 后端返回的是角色对象数组，需要提取ID
    selectedRoleIds.value = res.data.map(role => role.id)
  } catch (error) {
    Message.error('获取用户角色失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  getUserList()
}

// 新增用户
const handleAdd = () => {
  formTitle.value = '新增用户'
  userForm.value = {
    id: null,
    username: '',
    password: '',
    nickname: '',
    phone: '',
    email: ''
  }
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (record) => {
  formTitle.value = '编辑用户'
  userForm.value = { ...record }
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  try {
    await userFormRef.value.validate()
    const isEdit = userForm.value.id !== null
    const api = isEdit
      ? `/api/SysUser/${userForm.value.id}`
      : '/api/SysUser'
    const method = isEdit ? 'put' : 'post'
    
    const res = await request[method](api, userForm.value)
    Message.success(res.message)
    dialogVisible.value = false
    getUserList()
  } catch (error) {
    Message.error(error.message || '操作失败')
  }
}

// 取消表单
const handleCancel = () => {
  userFormRef.value.resetFields()
  dialogVisible.value = false
}

// 删除用户
const handleDelete = async (record) => {
  try {
    const res = await request.delete(`/api/SysUser/${record.id}`)
    Message.success(res.message)
    getUserList()
  } catch (error) {
    Message.error('删除失败')
  }
}

// 修改状态
const handleStatusChange = async (record, value) => {
  try {
    const status = value ? 1 : 0
    const res = await request.put(`/api/SysUser/${record.id}/status/${status}`)
    Message.success(res.message)
    getUserList()
  } catch (error) {
    Message.error('修改状态失败')
  }
}

// 分配角色
const handleRole = async (record) => {
  currentUser.value = record
  await getRoleList()
  await getUserRoles(record.id)
  roleDialogVisible.value = true
}

// 提交角色分配
const handleRoleSubmit = async () => {
  try {
    const res = await request.post(
      `/api/SysUser/${currentUser.value.id}/roles`,
      selectedRoleIds.value
    )
    Message.success(res.message)
    roleDialogVisible.value = false
    getUserList()
  } catch (error) {
    Message.error('分配角色失败')
  }
}

// 重置密码
const handleResetPwd = (record) => {
  pwdForm.value = {
    userId: record.id,
    newPassword: '',
    confirmPassword: ''
  }
  pwdDialogVisible.value = true
}

// 提交密码重置
const handlePwdSubmit = async () => {
  try {
    await pwdFormRef.value.validate()
    if (pwdForm.value.newPassword !== pwdForm.value.confirmPassword) {
      Message.error('两次输入的密码不一致')
      return
    }
    
    const res = await request.put(
      `/api/SysUser/${pwdForm.value.userId}/password`,
      { newPassword: pwdForm.value.newPassword }
    )
    Message.success(res.message)
    pwdDialogVisible.value = false
  } catch (error) {
    Message.error(error.message || '重置密码失败')
  }
}

// 角色过滤
const filterRole = (inputValue, item) => {
  return item.roleName.toLowerCase().includes(inputValue.toLowerCase())
}

// 分页变化
const onPageChange = (current) => {
  pagination.value.current = current
  getUserList()
}

// 格式化日期
const formatDate = (date) => {
  return date ? new Date(date).toLocaleString() : '-'
}

onMounted(() => {
  getUserList()
})
</script>

<style scoped>
.user-container {
  padding: 16px;
}

.search-bar {
  margin-bottom: 16px;
}
</style>